<!--
 * @Author: 瞿旺兴 18774621495@163.com
 * @Date: 2022-05-31 20:19:36
 * @LastEditors: 瞿旺兴 18774621495@163.com
 * @LastEditTime: 2022-06-08 17:48:53
 * @FilePath: \nien-vue3-admin\src\views\BusinessConfiguration\sellPriceManagement\components\EditPriceManagement.vue
 * @Description: 修改价格管理
-->
<template>
  <el-dialog
    v-model="visible"
    title="修改价格管理"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :before-close="handleCancel"
  >
    <div class="edit-box">
      加价
      <el-input-number v-model="addPrice" :controls="false"></el-input-number>
      <el-select v-model="priceType">
        <el-option
          v-for="(item, index) in [
            { label: '净加价', value: '1' },
            { label: '百分比', value: '2' },
          ]"
          :key="index"
          :value="item.value"
          :label="item.label"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="handleAddPrice">执行加价</el-button>
    </div>
    <div class="align-bottom">
      <inp-val-format ref="inpValRef" v-model:formatValue="batchValue" line-match-type="priceManage"></inp-val-format>
      <el-button type="primary" @click="batchEdit">批量修改</el-button>
      <el-checkbox v-model="longitudinalMode" size="default">纵向模式</el-checkbox>
    </div>
    <div class="btn-box">
      <el-button type="primary" @click="handleCopyCost">生成价格数据</el-button>
      <el-button type="primary" @click="handleCopySelling">复制价格数据</el-button>
    </div>
    <el-table v-loading="loading" :data="tableData">
      <el-table-column v-for="(el, index) in tableTitle" :key="index" :label="el">
        <template #default="{row}">
          <template v-if="el === '区间名称'">
            <el-input
              v-model="row[`${el}_${index}`].value"
              style="width: 100px"
              @change="handleSubmit(row, `${el}_${index}`)"
            ></el-input>
          </template>
          <template v-else>
            <el-input-number
              v-model.number="row[`${el}_${index}`].value"
              style="width: 100px"
              :controls="false"
              @change="handleSubmit(row, `${el}_${index}`)"
            ></el-input-number>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <el-button type="info" @click="handleCancel">取消</el-button>
      <el-button type="primary" :loading="saveLoading" @click="handleSave">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, defineExpose, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import InpValFormat from './InpValFormat.vue'
import { 
  siteSellingPartititonPriceInfoList,
  pricePartitionBatchAdd,
  copyCostPrice,
  copySellingPrice,
  sellingPriceSaveOrEdit } from '@/api/BusinessConfig/sellPriceManagement'

const props = defineProps({
  siteId: Number,
})

const tableData = ref([])
const tableTitle = ref([])
const loading = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const visible = ref<boolean>(false)
const longitudinalMode = ref<boolean>(false)
const priceSiteId = ref<number>()
const addPrice = ref<number>()
const priceType = ref<string>('1')

const getList = () => {
  loading.value = true
  siteSellingPartititonPriceInfoList(props.siteId, { priceSiteId: priceSiteId.value }).then(({ code, data }) => {
    if (code === 200) {
      tableData.value = []
      tableTitle.value = data[0].titles
      data.forEach(el1 => {
        const row = {}
        tableTitle.value.forEach((el3, index2) => {
          el1.rwos.forEach(el => {
            if (el.NAME == el3) {
              row[`${ el3 }_${ index2 }`] = {
                value: el.PRICE,
                id: el.ID,
              }
            }
          })
        })
        tableData.value.push(row)
      })

      console.log(tableTitle.value)
      console.log(tableData.value)
    }
  }).finally(() => {
    loading.value = false
  })
}

const handleSubmit = (row, key) => {
  console.log(row, key)
  const price = row[key].value
  if (price !== undefined && price !== '' && price !== null) {
    const countryPartitionIdstr = row[key].id
    const weightPartitionId = row.区间名称_0.id
    const pId = priceSiteId.value
    const data = {
      price,
      weightPartitionId,
      countryPartitionIdstr,
      priceSiteId: pId,
    }
    sellingPriceSaveOrEdit(data).then(res => {
      if (res.code == 200) {
        ElMessage.success('修改成功')
      }
    })
  }
}
    
const handleAddPrice = () => {
  tableData.value.forEach(el => {
    Object.keys(el).forEach(key => {
      const lastKey = key.substring(key.lastIndexOf('_') + 1)
      if (Number.isNaN(Number(lastKey)) || lastKey == '0') return
      if (priceType.value == '1') {
        el[key].value = Number(addPrice.value) + Number(el[key].value)
      } else if (priceType.value == '2') {
        el[key].value = +(((1 + Number(addPrice.value)) * Number(el[key].value)).toFixed(2))
      }
    })
  })
}
    
const handleCopySelling = () => {
  copySellingPrice(props.siteId, { priceSiteId: priceSiteId.value }).then(({ code, msg }) => {
    if (code === 200) {
      ElMessage.success(msg)
      getList()
    } else {
      ElMessage.error(msg)
    }
  })
}
const handleCopyCost = () => {
  copyCostPrice(props.siteId, { priceSiteId: priceSiteId.value }).then(({ code, msg }) => {
    if (code === 200) {
      ElMessage.success(msg)
      getList()
    } else {
      ElMessage.error(msg)
    }
  })
}

// 批量
const batchValue = ref([])
const batchEdit = () => {
  if (longitudinalMode.value) {
    // 纵向
    for (let i = 0; i < batchValue.value.length; i++) {
      const item = batchValue.value[i]
      if (tableTitle.value.length - 1 < i) break
      if (item.length > tableData.value.length) item.length = tableData.value.length
      console.log(item, '2222')
      item.forEach((p, index) => {
        tableData.value[index][`${ tableTitle.value[i + 1] }_${ i + 1 }`].value = +p || 0
      })
    }
  } else {
    // 横向
    for (let i = 0; i < batchValue.value.length; i++) {
      const item = batchValue.value[i]
      if (tableData.value.length - 1 < i) break
      console.log(item, tableTitle.value)
      if (item.length > tableTitle.value.length - 1) item.length = tableTitle.value.length - 1
      item.forEach((p, index) => {
        tableData.value[i][`${ tableTitle.value[index + 1] }_${ index + 1 }`].value = +p || 0
      })
    }
  }
}

const handleSave = () => {
  const regIsNumber = /^\d+(\.\d+)?$/
  const data = []
  let index0Value = null
  tableData.value.forEach(ele => {
    Object.keys(ele).forEach((key, index) => {
      if (index === 0) {
        index0Value = ele[key].id
        return
      }
      const keyStr = key.lastIndexOf('_')
      const keyIndex = key.substring(keyStr + 1, key.length)
      if (!regIsNumber.test(keyIndex)) return
      const model = {
        weightPartitionId: index0Value,
        countryPartitionIdstr: ele[key].id,
        price: ele[key].value,
      }
      data.push(model)
    })
  })
  const params = {
    priceSiteId: priceSiteId.value,
    partititonPriceDtos: data, 
  }
  saveLoading.value = true

  pricePartitionBatchAdd(params).then(({ code, msg }) => {
    if (code === 200) {
      ElMessage.success(msg)
      getList()
    }
  }).finally(() => {
    saveLoading.value = false
  })
}

const inpValRef = ref()
const handleCancel = () => {
  visible.value = false
  addPrice.value = undefined
  inpValRef.value.reset()
  batchValue.value = []
}

const open = (id) => {
  priceSiteId.value = id
  visible.value = true
  getList()
}

defineExpose({
  open,
})
</script>

<style lang="less" scoped>
.edit-box{
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  .el-input-number{
     width: 160px;
     margin: 0 10px;
  }
  .el-select{
     margin-right:20px
  }
}

.align-bottom{
  display: flex;
  align-items: flex-end;
  margin-bottom: 16px;

  .el-textarea{
     width: 214px;
  }
  .el-button{
    margin: 0 20px
  }
  .el-checkbox{
    height: 20px;
    line-height: 20px;
  }
}

.btn-box{
  margin-bottom: 12px;
}
</style>